import click
from watchlist import app,db
from watchlist.models import User,Movie
@app.cli.command()
@click.option("--drop",is_flag=True,help="Create after drop ")
def initdb(drop):
    """ Initialize the database"""
    if drop:
        db.drop_all()
    db.create_all()
    click.echo(" ---Initialize The Database Done--- ")


@app.cli.command()
def forge():
    """Generate fake data """
    db.create_all()
    ## 准备一些虚拟数据
    name = 'haiShen'
    movies = [
        {'title': 'My Neighbor Totoro', 'year': '1988'},
        {'title': 'Dead Poets Society', 'year': '1989'},
        {'title': 'A Perfect World', 'year': '1993'},
        {'title': 'Leon', 'year': '1994'},
        {'title': 'Mahjong', 'year': '1996'},
        {'title': 'Swallowtail Butterfly', 'year': '1996'},
        {'title': 'King of Comedy', 'year': '1999'},
        {'title': 'Devils on the Doorstep', 'year': '1999'},
        {'title': 'WALL-E', 'year': '2008'},
        {'title': 'The Pork of Music', 'year': '2012'},
    ]
    user = User(name=name)
    db.session.add(user)
    for m in movies:
        movie = Movie(title=m['title'],year=m['year'])
        db.session.add(movie)

    db.session.commit()
    click.echo('Initialized Database Done')

@app.cli.command()
@click.option("--username",prompt=True,help="The username used to login.")
@click.option("--password",prompt=True,hide_input=True,confirmation_prompt=True,help="The password used to login.")

# @click.option('--username', prompt=True, help='The username used to login.')
# @click.option('--password', prompt=True, hide_input=True, confirmation_prompt=True, help='The password used to login.')
def admin(username,password):
    """ create user """
    db.create_all()

    user = User.query.first()
    if user is not None:
        click.echo("Update User...")
        user.username = username
        user.set_password(password=password)    ## 200310

    else:
        click.echo("Creating User")
        user = User(username=username,name='Admin')
        user.set_password(password=password)
        db.session.add(user)

    db.session.commit()
    click.echo(" ---Done--- ")